package com.smartleanx.module.hrm.intergration;

import javax.annotation.Resource;

import com.smartleanx.module.hrm.service.salary.HrmSalaryTableConfigService;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.smartleanx.framework.common.util.object.BeanUtils;
import com.smartleanx.framework.tenant.core.aop.TenantIgnore;
import com.smartleanx.framework.tenant.core.context.TenantContextHolder;
import com.smartleanx.framework.tenant.core.util.TenantUtils;
import com.smartleanx.module.hrm.controller.admin.tenant.vo.TenantSaveReqVO;
import com.smartleanx.module.hrm.eums.risk.RiskLevelEnum;
import com.smartleanx.module.hrm.eums.risk.RiskTypeEnum;
import com.smartleanx.module.hrm.service.companysystemtype.CompanySystemTypeService;
import com.smartleanx.module.hrm.service.risk.RiskService;
import com.smartleanx.module.hrm.service.tenant.TenantIgnoreIdService;
import com.smartleanx.module.system.api.tenant.TenantApi;
import com.smartleanx.module.system.api.tenant.dto.TenantRespDTO;
import com.smartleanx.module.system.api.tenant.dto.TenantSaveReqDTO;

/**
 * 租户服务
 *
 * @author tengcj
 * @since 2024/7/23
 */
@Component
public class TenantServiceProvider {

    @Resource
    private TenantApi tenantApi;

    @Resource
    private CompanySystemTypeService companySystemTypeService;

    @Resource
    private RiskService riskService;

    @Resource
    private BpmServiceProvider bpmServiceProvider;

    @Resource
    private TenantIgnoreIdService tenantIgnoreIdService;

    @Resource
    private HrmSalaryTableConfigService hrmSalaryTableConfigService;

    @Transactional(rollbackFor = Exception.class)
    public Long createTenant(TenantSaveReqVO createReqVO) {
        Long tenantId = tenantApi.createTenant(BeanUtils.toBean(createReqVO, TenantSaveReqDTO.class)).getCheckedData();

        TenantUtils.execute(tenantId, () -> {
            // 创建制度分类
            companySystemTypeService.curdInitializeCompanyType();
            // 初始化风险
            riskService.addRisk(null, RiskTypeEnum.NO_REGULATION.getCode(), RiskLevelEnum.MAJOR.getLevel(), null);
            // 初始化工作流
            bpmServiceProvider.initBpmModelNew();
        });

        // 初始化租户电子合同控件
        tenantIgnoreIdService.initTemplateComponent(tenantId);

        //一坨初始化
        hrmSalaryTableConfigService.init(tenantId.intValue());

        return tenantId;
    }

    @Transactional(rollbackFor = Exception.class)
    public Long updateTenantBpm(long tenantId) {

        TenantUtils.execute(tenantId, () -> {
            // 初始化工作流
            bpmServiceProvider.initBpmModelNew();
        });

        return tenantId;
    }

    public TenantRespDTO getCurrentTenant() {
        return tenantApi.getTenant(TenantContextHolder.getTenantId()).getCheckedData();
    }

}
